package com.indra.archetypeweb.service;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.indra.archetypeweb.dao.user.UserDao;
import com.indra.archetypeweb.entity.user.User;

@Service("userService")
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = userDao.findByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("user not found");
		}

		GrantedAuthority authority = new SimpleGrantedAuthority(user.getRole());
		return new org.springframework.security.core.userdetails.User(
				user.getUsername(), user.getPassword(),
				Collections.singleton(authority));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.indra.archetypeweb.service.UserService#findByUsername(java.lang.String
	 * )
	 */
	@Override
	public User findByUsername(String username) {
		return userDao.findByUsername(username);
	}

	@Override
	@Transactional
	public void register(User newUser) {
		userDao.create(newUser);

	}

	@Override
	public List<User> showAllUsers() {
		return userDao.findAll();
	}

}
